package ru.mcfr.oxygen.util.web;

import org.apache.log4j.Logger;
import sun.misc.BASE64Encoder;
import sun.net.www.protocol.http.HttpURLConnection;

import java.io.*;
import java.net.InetSocketAddress;
import java.net.MalformedURLException;
import java.net.Proxy;
import java.net.URL;
import java.util.Properties;

public class AbstractWebConnector {

    public static Logger logger = Logger.getLogger(AbstractWebConnector.class.getName());

    private boolean useProxy;
    private String proxyAddress;
    private Integer proxyPort;
    private String userName;
    private String userPass;

    public AbstractWebConnector(Properties props) {
        this.proxyAddress = props.getProperty("proxy-server");
        this.proxyPort = Integer.valueOf(props.getProperty("proxy-port", "8080"));
        this.useProxy = Boolean.valueOf(props.getProperty("use-proxy"));
        this.userName = props.getProperty("proxy-user-name");
        this.userPass = props.getProperty("proxy-user-password");
    }

    protected String getFromURL(String sUrl) {
        try {
            return getFromURL(new URL(sUrl));
        } catch (MalformedURLException e) {
            logger.error(e);
            return null;
        }
    }

    protected String getFromURL(URL url) {

        try {

            HttpURLConnection urlConn;
            if (this.useProxy) {
                Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(this.proxyAddress, this.proxyPort));
                urlConn = new HttpURLConnection(url, proxy);
                BASE64Encoder encoder = new BASE64Encoder();
                String passPhrase = this.userName + ":" + this.userPass;
                String encodedUserPwd = encoder.encode(passPhrase.getBytes());
                urlConn.setRequestProperty("Proxy-Authorization", "Basic " + encodedUserPwd);
            } else
                urlConn = new HttpURLConnection(url, null);

            urlConn.setRequestMethod("GET");
            urlConn.setDoInput(true);
            urlConn.setDoOutput(true);
            urlConn.setUseCaches(false);

            urlConn.connect();

            InputStream input = urlConn.getInputStream();

            if (input != null & urlConn.getResponseCode() < HttpURLConnection.HTTP_MULT_CHOICE) {
                Writer writer = new StringWriter();

                char[] buffer = new char[1024];
                try {
                    Reader reader = new BufferedReader(new InputStreamReader(input, "UTF-8"));
                    int n;
                    while ((n = reader.read(buffer)) != -1) {
                        writer.write(buffer, 0, n);
                    }
                } finally {
                    input.close();
                    urlConn.disconnect();
                }
                return writer.toString();
            } else {
                return "";
            }
        } catch (IOException e) {
            logger.error(e);
        }

        return null;
    }

}
